import React, { useState, useRef, useEffect } from 'react';
import { Task, TaskExecutorProps } from './types';


export const TaskExecutor: React.FC<TaskExecutorProps> = ({ 
  tasks,
  onBatchExecute,
  isExecuting 
}) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTasks, setSelectedTasks] = useState<string[]>([]);
  const [expandedCategories, setExpandedCategories] = useState<string[]>([]);
  const dropdownRef = useRef<HTMLDivElement>(null);


  // 处理点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 按分类分组任务
  const tasksByCategory = tasks.reduce((acc: { [key: string]: Task[] }, task) => {
    // 确保所有任务都有分类，如果没有则使用"未分类"
    const category = task.category || "未分类";
    
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(task);
    return acc;
  }, {});

  // 过滤任务选项
  const getFilteredTasks = () => {
    if (!searchQuery) return tasksByCategory;
    
    const filtered: { [key: string]: Task[] } = {};
    
    Object.entries(tasksByCategory).forEach(([category, categoryTasks]) => {
      const filteredCategoryTasks = categoryTasks.filter(task => 
        task.taskTitle.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (task.taskGuide && task.taskGuide.toLowerCase().includes(searchQuery.toLowerCase()))
      );
      
      if (filteredCategoryTasks.length > 0) {
        filtered[category] = filteredCategoryTasks;
      }
    });
    
    return filtered;
  };

  // 处理任务选择
  const handleTaskSelection = (taskId: string) => {
    if (isExecuting) return; // 任务执行中不允许选择
    
    setSelectedTasks(prev => {
      if (prev.includes(taskId)) {
        return prev.filter(id => id !== taskId);
      } else {
        // 限制最多选择3个任务
        return prev.length < 3 ? [...prev, taskId] : prev;
      }
    });
  };

  // 处理类别展开/折叠
  const toggleCategory = (category: string, event: React.MouseEvent) => {
    event.stopPropagation();
    setExpandedCategories(prev => {
      if (prev.includes(category)) {
        return prev.filter(c => c !== category);
      } else {
        return [...prev, category];
      }
    });
  };

  // 处理类别下所有任务的选择
  const handleCategorySelection = (categoryTasks: Task[]) => {
    if (isExecuting) return; // 任务执行中不允许选择
    
    const taskIds = categoryTasks.map(task => task.id);
    const allSelected = taskIds.every(id => selectedTasks.includes(id));
    
    if (allSelected) {
      setSelectedTasks(prev => prev.filter(id => !taskIds.includes(id)));
    } else {
      setSelectedTasks([...taskIds]);
    }
  };

  // 移除选中的任务
  const removeSelection = (taskId: string) => {
    if (isExecuting) return; // 任务执行中不允许移除
    setSelectedTasks(prev => prev.filter(id => id !== taskId));
  };

  // 清除所有选择
  const clearSelections = () => {
    if (isExecuting) return; // 任务执行中不允许清除
    setSelectedTasks([]);
  };

  // 获取已选任务的显示信息
  const getSelectedTasksDisplay = () => {
    return selectedTasks.map(taskId => {
      const task = tasks.find(t => t.id === taskId);
      return {
        id: taskId,
        title: task?.taskTitle || '未知任务'
      };
    });
  };

  // 执行选中的任务
  const handleExecuteTasks = () => {
    if (selectedTasks.length === 0 || isExecuting) return;
    onBatchExecute(selectedTasks);
    setSelectedTasks([]);
    setIsDropdownOpen(false);
  };

  // 生成禁用状态下的类名
  const getDisabledClass = (baseClass: string) => {
    return isExecuting 
      ? `${baseClass} opacity-60 cursor-not-allowed` 
      : baseClass;
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md">
      <div className="p-6">
        <h2 className="text-xl font-semibold mb-4 dark:text-white">执行任务</h2>
        
        {isExecuting && (
          <div className="mb-4 p-2 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md text-yellow-700 dark:text-yellow-300 flex items-center">
            <svg className="w-5 h-5 mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            正在执行任务，请等待当前任务完成后再选择新任务
          </div>
        )}
        
        <div className="space-y-4">
          <div className="relative" ref={dropdownRef}>
            <h3 className="text-sm font-medium mb-2 dark:text-gray-300">选择要执行的任务</h3>

            {/* 已选任务标签显示 */}
            {selectedTasks.length > 0 && (
              <div className="flex flex-wrap gap-2 mb-2">
                <div className="flex items-center text-sm text-gray-600 dark:text-gray-400">
                  {selectedTasks.length} selected:
                </div>
                {getSelectedTasksDisplay().map(task => (
                  <div
                    key={task.id}
                    className="flex items-center gap-1 px-2 py-1 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-md text-sm"
                  >
                    {task.title}
                    <button
                      disabled={isExecuting}
                      onClick={(e) => {
                        e.stopPropagation();
                        if (!isExecuting) removeSelection(task.id);
                      }}
                      className={`text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-200 ${isExecuting ? 'opacity-60 cursor-not-allowed' : ''}`}
                    >
                      ×
                    </button>
                  </div>
                ))}
                <button
                  disabled={isExecuting}
                  onClick={clearSelections}
                  className={`text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 ${isExecuting ? 'opacity-60 cursor-not-allowed' : ''}`}
                >
                  Clear
                </button>
              </div>
            )}

            {/* 搜索框和下拉触发器 */}
            <div
              className={getDisabledClass("w-full p-2 border rounded-md flex items-center gap-2 cursor-pointer dark:bg-gray-700 dark:border-gray-600")}
              onClick={() => !isExecuting && setIsDropdownOpen(prev => !prev)}
            >
              {selectedTasks.length > 0 ? (
                <div className="flex flex-1 flex-wrap gap-2">
                  {getSelectedTasksDisplay().map(task => (
                    <div
                      key={task.id}
                      className="flex items-center gap-1 px-2 py-1 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-md text-sm"
                      onClick={(e) => e.stopPropagation()}
                    >
                      {task.title}
                      <button
                        disabled={isExecuting}
                        onClick={(e) => {
                          e.stopPropagation();
                          if (!isExecuting) removeSelection(task.id);
                        }}
                        className={`text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-200 ${isExecuting ? 'opacity-60 cursor-not-allowed' : ''}`}
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              ) : (
                <span className="flex-1 text-gray-400">选择任务...</span>
              )}
              <button
                disabled={isExecuting}
                className={`text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transform transition-transform duration-200 ${
                  isDropdownOpen ? 'rotate-180' : ''
                } ${isExecuting ? 'opacity-60 cursor-not-allowed' : ''}`}
                onClick={(e) => {
                  e.stopPropagation();
                  if (!isExecuting) setIsDropdownOpen(prev => !prev);
                }}
              >
                ▼
              </button>
            </div>

            {/* 下拉选项列表 */}
            {isDropdownOpen && !isExecuting && (
              <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-md shadow-lg max-h-[400px] overflow-hidden">
                {/* 搜索框 */}
                <div className="sticky top-0 p-2 bg-white dark:bg-gray-800 border-b dark:border-gray-700">
                  <div className="relative">
                    <input
                      type="text"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      placeholder="搜索任务..."
                      className="w-full pl-8 pr-2 py-1.5 border rounded-md outline-none dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                      onClick={(e) => e.stopPropagation()}
                    />
                    <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-400">
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                      </svg>
                    </span>
                  </div>
                </div>

                <div className="overflow-auto max-h-[320px]">
                  {Object.entries(getFilteredTasks()).map(([category, categoryTasks]) => (
                    categoryTasks.length > 0 && (
                      <div key={category} className="border-b last:border-b-0 dark:border-gray-700">
                        <label
                          className="flex items-center gap-2 px-4 py-2 bg-gray-50 dark:bg-gray-700 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600"
                        >
                          <input
                            type="checkbox"
                            checked={categoryTasks.every(task => selectedTasks.includes(task.id))}
                            onChange={() => handleCategorySelection(categoryTasks)}
                            className="rounded text-blue-500 dark:bg-gray-700"
                            disabled={isExecuting}
                          />
                          <div className="flex items-center gap-2 flex-1">
                            <span className="text-gray-700 dark:text-gray-200 font-medium">{category}</span>
                            <span className="text-sm text-gray-500 dark:text-gray-400">({categoryTasks.length})</span>
                          </div>
                          <button
                            onClick={(e) => toggleCategory(category, e)}
                            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
                          >
                            <span className={`transform transition-transform duration-200 inline-block ${
                              expandedCategories.includes(category) ? 'rotate-180' : ''
                            }`}>
                              ▼
                            </span>
                          </button>
                        </label>
                        
                        <div className={`transition-all duration-200 ${
                          expandedCategories.includes(category)
                            ? 'max-h-[1000px] opacity-100'
                            : 'max-h-0 opacity-0'
                        } overflow-hidden`}>
                          <div className="bg-white dark:bg-gray-800 pl-8">
                            {categoryTasks.map(task => (
                              <label
                                key={task.id}
                                className="flex items-center gap-2 px-4 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
                              >
                                <input
                                  type="checkbox"
                                  checked={selectedTasks.includes(task.id)}
                                  onChange={() => handleTaskSelection(task.id)}
                                  className="rounded text-blue-500 dark:bg-gray-700"
                                  disabled={isExecuting}
                                />
                                <div>
                                  <div className="text-gray-800 dark:text-gray-200">{task.taskTitle}</div>
                                  <div className="text-xs text-gray-500 dark:text-gray-400 truncate">
                                    {task.taskGuide}
                                  </div>
                                </div>
                              </label>
                            ))}
                          </div>
                        </div>
                      </div>
                    )
                  ))}
                  
                  {Object.keys(getFilteredTasks()).length === 0 && (
                    <div className="px-4 py-3 text-center text-gray-500 dark:text-gray-400">
                      没有找到匹配的任务
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          <p className="text-sm text-gray-500 dark:text-gray-400">
            可以选择一个类别或最多三个单独的任务。
          </p>

          <button
            className="w-full bg-blue-500 text-white px-6 py-2 rounded-md flex items-center justify-center gap-2 hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed dark:disabled:bg-gray-700"
            disabled={selectedTasks.length === 0 || isExecuting}
            onClick={handleExecuteTasks}
          >
            <span>▶</span>
            执行 {selectedTasks.length} 个任务
          </button>
        </div>
      </div>
    </div>
  );
}; 

export default TaskExecutor;